<?php
namespace Home\Model;
use Think\Model;
class PaymentInfoModel extends CommonModel {
	
	public function completeOnlinePayFlow($flowId,$tradeNo,$payType){
		$onlinePayFlowSrv = D('PaymentOnlineFlow');
		$flowInfo = $onlinePayFlowSrv->where("flow_id = '".$flowId."'")->find();
		if(empty($flowInfo)){
			$result['isok'] = false;
			$result['msg'] = '流水号异常';
			return $result;
		}
		if($flowInfo['status']!=0){
			$result['isok'] = false;
			$result['msg'] = '该流水单号不可支付';
			return $result;
		}
		$realPay = num_f($flowInfo['should_pay']);
		//执行update
		$data['real_pay'] = $realPay;
		$data['trade_no'] = $tradeNo;
		$data['status'] = 1;
		$db_res = $onlinePayFlowSrv->where("flow_id = '".$flowId."'")->save($data);
		if(!$db_res){
			$result['isok'] = false;
			$result['msg'] = '更新流水单号失败';
			return $result;
		}
		$res_finish = $this->finishPaymentPay($flowInfo['relation_id'],$realPay,$payType,$tradeNo);
		if(!$res_finish){
			$result['isok'] = false;
			$result['msg'] = '账单支付失败';
			return $result;
		}
		$result['isok'] = true;
		$result['msg'] = '账单支付成功';
		return $result;
	}
	
	//完成对账单的付款
	public function finishPaymentPay($payment_id,$real_payment,$payment_type,$payment_doc_id){
		$paymentInfo = D('PaymentInfo');
		$data['real_payment'] = $real_payment;
		$data['payment_type'] = $payment_type;
		$data['payment_doc_id'] = $payment_doc_id;
		$data['payment_status'] = C('PAYMENT_STATUS.PAYED_CLOSE');
		$paymentInfo->where("payment_id = '".$payment_id."'")->save($data);
		// 验证需不需要减库存
		$db_res = $this->query("SELECT od.*,oi.order_type,pi.payment_id FROM ar_shop.order_detail AS od
		LEFT JOIN ar_shop.order_info AS oi ON oi.order_id = od.order_id
		LEFT JOIN ar_shop.payment_info AS pi ON pi.order_id = oi.order_id
		WHERE pi.payment_id = '".$payment_id."'");
		if(!empty($db_res[0]['order_type']) && $db_res[0]['order_type'] == 'common'){
			//支付后减库存
			$commodityLimit = D('CommodityLimit');
			foreach($db_res as $db_one){// 普通商品 减库存
				$commodityLimit->doLimitByOrder($db_one['order_id'],$db_one['commodity_id'],$db_one['order_num'],1,-1);
			}
		}
		$result['isok'] = true;
		$result['msg'] = '账单更新成功';
		return $result;
	}
	
	
}

?>